<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import SlideVerify from '@/components/slide-verify.vue'
import { setRoutesByRole } from '@/router/routerHelper'
import { useCodeLogin, useGetUserInfo, useSendSms } from '@fl/api/mall-api'
import { SubmitBtn } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { ElForm, ElFormItem } from 'element-plus'

const { push } = useRouter()

const { createMessage } = useMessage()
const verifyRef = ref()

type IForm = {
    mobile: string
    verificationCode: string
}

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<IForm>({
    mobile: '',
    verificationCode: '',
})

const rules = reactive<FormRules<IForm>>({
    mobile: [
        {
            message: '请输入手机号',
            required: true,
        },
        { message: '手机号码格式不正确', pattern: /^1[3-9]\d{9}$/, trigger: 'blur' },
    ],
    verificationCode: [
        {
            message: '请输入验证码',
            required: true,
        },
    ],
})

const veryfyCodeFirstSending = ref(false)
const isVerify = ref(false)
const countdown = ref(0)
const verifyLabel = computed(() => {
    if (unref(veryfyCodeFirstSending)) {
        if (unref(countdown) > 0)
            return `${unref(countdown)}秒后重发`
        else
            return '重新发送'
    }
    else { return '发送验证码' }
})

const { isPending: isPendingSendSms, mutate: mutateSendSms } = useSendSms()
const { isPending: isPendingLogin, mutateAsync: mutateLoginAsync } = useCodeLogin()
const { isLoading: isLoadingUserInfo, refetch: refetchUserInfo } = useGetUserInfo(false)

const isPending = computed(() => isPendingLogin.value || isLoadingUserInfo.value) // 是否正常

async function sendVerifyCode() {
    const isValid = await unref(ruleFormRef)!.validateField('mobile')
    if (isValid) {
        // 如果已经是真实的人类, 允许提交表单
        if (verifyRef.value.isHuman)
            await verifySuccess()
        else
            isVerify.value = true
    }
}

async function verifySuccess() {
    mutateSendSms({ mobile: ruleForm.mobile }, {
        onSuccess: () => {
            // 启动倒计时
            veryfyCodeFirstSending.value = true
            countdown.value = 60
            startCountdown()
        },
    })
}

function startCountdown() {
    const interval = setInterval(() => {
        countdown.value = countdown.value - 1
        if (unref(countdown) === 0)
            clearInterval(interval)
    }, 1000)
}

function forgetPassword() {
    push('/forget-password')
}

async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return

    const isValid = await formEl.validate()
    if (isValid) {
        const result = await mutateLoginAsync(ruleForm)
        if (result) {
            createMessage.success('登录成功')
            await refetchUserInfo()
            await setRoutesByRole()
            // await setRoutesByRoleByFrontend()
        }
    }
}
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="flex flex-col gap-12">
            <ElFormItem label="手机号"
                        prop="mobile"
            >
                <el-input v-model.trim="ruleForm.mobile"
                          placeholder="请输入手机号"
                          maxlength="11"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="验证码"
                        prop="verificationCode"
            >
                <div class="flex w-full items-center">
                    <el-input v-model.trim="ruleForm.verificationCode"
                              placeholder="请输入验证码"
                              size="large"
                              minlength="6"
                              maxlength="6"
                              class="flex-1"
                    />

                    <SubmitBtn type="primary"
                               class="ml-8 h-40 w-100"
                               :disabled="countdown > 0"
                               :loading="isPendingSendSms"
                               @click="sendVerifyCode"
                    >
                        {{ verifyLabel }}
                    </SubmitBtn>
                </div>
            </ElFormItem>
        </div>

        <div class="forget"
             @click="forgetPassword"
        >
            忘记密码
        </div>

        <SubmitBtn type="primary"
                   native-type="submit"
                   class="btn rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                   size="large"
                   :loading="isPending"
                   @click="submitForm(ruleFormRef)"
        >
            登录
        </SubmitBtn>

        <!-- <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="isPending"
                       @click="submitForm(ruleFormRef)"
            >
                登录
            </SubmitBtn>
        </ElFormItem> -->
    </ElForm>

    <SlideVerify ref="verifyRef"
                 v-model:visible="isVerify"
                 @success="verifySuccess"
    />
</template>

<style lang="scss" scoped>
@function toVw($px) {
    @return #{calc(#{$px} * 100 / 1920 * 1vw)};
}
@function toVh($px) {
    @return #{calc(#{$px} * 100 / 1080 * 1vh)};
}
.forget {
    text-align: right;
    font-size: 14px;
    color: #da0004;
    cursor: pointer;
}
.btn {
    margin-top: toVh(20);
}
</style>
